import { _decorator, Component, director, EditBox } from "cc"
import NetworkManager from "../Global/NetworkManager"
import { ApiMsgEnum } from "../Common"
import DataManager from "../Global/DataManager"
import { SceneEnum } from "../Enum"
const { ccclass } = _decorator

@ccclass("LoginManager")
export class LoginManager extends Component {
    input: EditBox

    onLoad() {
        this.input = this.getComponentInChildren(EditBox)
        director.preloadScene(SceneEnum.Hall)
    }

    async start() {
        await NetworkManager.Instance.connect()
    }

    async handClick() {
        if (!NetworkManager.Instance.isConnected) {
            console.error("网络未连接")
            await NetworkManager.Instance.connect()
            return
        }

        const nickname = this.input.string.trim()
        if (!nickname) {
            console.error("昵称不能为空")
            return
        }

        // 调用登录接口
        const { success, error, res } = await NetworkManager.Instance.callApi(
            ApiMsgEnum.ApiPlayerJoin,
            { nickname }
        )
        if (!success) {
            console.error("登录失败", error)
            return
        }
        console.log("登录成功", res)

        DataManager.Instance.myPlayerId = res.player.id
        director.loadScene(SceneEnum.Hall)
    }
}